﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using produccion.clases;
using System.Data;
using System.IO;
using System.Collections.ObjectModel;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para frmSusti.xaml
    /// </summary>
    public partial class frmSusti : Window
    {
        CLSMAESUSP MaeSus = new CLSMAESUSP();
        CLSMAEMAT MaeMat = new CLSMAEMAT();
        CLSMAEMTP MaeMtp = new CLSMAEMTP();
        CLSMAECOLP MaeColP = new CLSMAECOLP();
        ObservableCollection<RegSus> Lista = new ObservableCollection<RegSus>(); 
        DataTable dtSus = new DataTable();

        MDOgeneral MdoGeneral = new MDOgeneral();//FJRF - Para traer las funciones del modulo general
        public frmSusti()
        {
            InitializeComponent();
        }

        private void txtCodMat_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txtCodMat.Text.Length == 10)
            {
                Lista.Clear();
                dgSus.ItemsSource = null;
                MaeMat.CODMAT_MAT = txtCodMat.Text.Substring(0, 6);
                if (MaeMat.ExisteMateria())
                {
                    MaeColP.CODCOL_COL = txtCodMat.Text.Substring(6, 4);
                    if (MaeColP.existe())
                    {
                        MaeMat.Consultar();
                        MaeColP.consultar();
                        txtNomMatCam.Text = MaeMat.NOMMAT_MAT + " " + MaeColP.NOMCOL_COL;
                        BitmapImage b = new BitmapImage();
                        if (File.Exists(MDOgeneral.Fotos_ARTESA + txtCodMat.Text + ".jpg"))
                        {
                            b.BeginInit();
                            b.UriSource = new Uri(MDOgeneral.Fotos_ARTESA + txtCodMat.Text + ".jpg");
                            b.EndInit();
                            imgFoto.Stretch = Stretch.Fill;
                            imgFoto.Source = b;
                        }
                        else
                        {
                            imgFoto.Source = null;
                        }
                        MaeMtp.CODMAT_MTP = txtCodMat.Text.Substring(0, 6);
                        MaeMtp.CODCOL_MTP = txtCodMat.Text.Substring(6, 4);
                        if (MaeMtp.existe())
                        {
                            MaeSus.MTPPPA_SUS = txtCodMat.Text;
                            dtSus = MaeSus.Consultar();
                            if (dtSus.Rows.Count > 0)
                            {
                                for (int i = 0; i < dtSus.Rows.Count; i++)
                                {
                                    String StrCodigoMaterial = dtSus.Rows[i][0].ToString().Substring(0, 6);//FJRF - Extraemos el codigo
                                    String StrNombreMaterial = MdoGeneral.StrRetornarUnSoloCampo("nommat_mat", "NombreMaterial", "maemat", "CODMAT_MAT = '" + StrCodigoMaterial + "' ");//FJRF - Buscamos el mombre del material

                                    Lista.Add(new RegSus { MTPSUS_SUS = dtSus.Rows[i][0].ToString(), DESCRIPCION = StrNombreMaterial, OBSERV_SUS = dtSus.Rows[i][1].ToString() });
                                }
                            }
                            else
                            {
                                Lista.Add(new RegSus { MTPSUS_SUS = "", DESCRIPCION = "", OBSERV_SUS = "" });
                            }
                            dgSus.ItemsSource = Lista;
                        }
                        else
                        {
                            MessageBox.Show("No existe la materia prima!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                            txtCodMat.Text = "";
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("No existe el color!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                        txtCodMat.Text = "";
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("No existe el material!", "Cambiar material", MessageBoxButton.OK, MessageBoxImage.Warning);
                    txtCodMat.Text = "";
                    return;
                }
            }
            else
            {
                LimpiarControles();
            }
        }

        public void LimpiarControles()
        {
            imgFoto.Source = null;
            txtNomMatCam.Text = "";
            dgSus.ItemsSource = null;
            Lista.Clear();
            Lista.Add(new RegSus { MTPSUS_SUS = "", DESCRIPCION = "", OBSERV_SUS = "" });
            dgSus.ItemsSource = Lista;
        }

        private void btnGrabar_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Está seguro de grabar los cambios?", "Sustitutos", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                MaeSus.MTPPPA_SUS = txtCodMat.Text;
                MaeSus.Eliminar();
                for (int i = 0; i < Lista.Count; i++)
                {
                    RegSus Rg = new RegSus();
                    Rg = Lista[i];
                    if (Rg.MTPSUS_SUS != "")
                    {
                        MaeSus.MTPSUS_SUS = Rg.MTPSUS_SUS;
                        MaeSus.OBSERV_SUS = Rg.OBSERV_SUS;
                        MaeSus.CONSEC_SUS = MaeSus.Consecutivo();
                        MaeSus.Insertar();
                    }
                }
                LimpiarControles();
                txtCodMat.Text = "";
                new MDOgeneral.notificar(wPnot, "Los cambios fueron guardados correctamente", true);
            }
        }

        private void btnBuscarMatCam_Click(object sender, RoutedEventArgs e)
        {
            FRMBuscarCol frm = new FRMBuscarCol();
            frm.RequiereColor = true;
            frm.EsReferencia = false;
            frm.ShowDialog();
            if (!String.IsNullOrEmpty(frm.Retorno))
            {
                txtCodMat.Text = frm.Retorno.Substring(0, 8);
            }
        }

        private void btnSalir_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void dgSus_KeyDown(object sender, KeyEventArgs e)
        {
            int i = dgSus.SelectedIndex; ;
            int j = dgSus.CurrentCell.Column.DisplayIndex;
            RegSus Rg = new RegSus();
            if (j == 0)
            {
                if (e.Key == Key.F2)
                {
                    FRMBuscarCol frm = new FRMBuscarCol();
                    frm.EsReferencia = false;
                    frm.RequiereColor = true;
                    frm.ShowDialog();
                    if (frm.Retorno == "")
                    {
                        for (int k = 0; k < frm.dtRetorno.Rows.Count; k++)
                        {
                            if ((k + i) > i)
                            {
                                Lista.Add(new RegSus { MTPSUS_SUS = "" });
                            }
                            Rg = Lista[(i + k)];
                            Rg.MTPSUS_SUS = MdoGeneral.PasarCadenaYRetornarCodigoONombre(frm.dtRetorno.Rows[k][0].ToString(), "-", "Codigo");
                            Rg.DESCRIPCION = MdoGeneral.PasarCadenaYRetornarCodigoONombre(frm.dtRetorno.Rows[k][0].ToString(), "-", "Nombre");
                        }
                    }
                    else
                    {
                        Rg = Lista[i];
                        Rg.MTPSUS_SUS = MdoGeneral.PasarCadenaYRetornarCodigoONombre(frm.Retorno, "-", "Codigo");
                        Rg.DESCRIPCION = MdoGeneral.PasarCadenaYRetornarCodigoONombre(frm.Retorno, "-", "Nombre");
                    }
                }
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(txtCodMat);
        }

        private void dgSus_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.Enter && elemento != null)
            {
                e.Handled = true;
                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }
    }

    public class RegSus: ObservableObject
    {
        string  mtpsus_sus, observ_sus, descripcion;
        CLSMAEMAT Mat = new CLSMAEMAT();
        public string MTPSUS_SUS
        {
            get { return mtpsus_sus; }
            set
            {
                mtpsus_sus = value;
                if (mtpsus_sus.Length == 8)
                {
                    Mat.CODMAT_MAT = mtpsus_sus.Substring(0, 6);
                    Mat.Consultar();
                    DESCRIPCION = Mat.NOMMAT_MAT;
                }
                RaisePropertyChangedEvent("MTPSUS_SUS");
            }
        }

        public string DESCRIPCION
        {
            get { return descripcion; }
            set
            {
                descripcion = value;
                RaisePropertyChangedEvent("DESCRIPCION");
            }
        }

        public string OBSERV_SUS
        {
            get { return observ_sus; }
            set
            {
                observ_sus = value;
                RaisePropertyChangedEvent("OBSERV_SUS");
            }
        }
    }
}
